﻿using SAD_Assignment1.BLO;
using SAD_Assignment1.DTO;
using SAD_Assignment1.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SAD_Assignment1.Admin
{
    public partial class AccountList : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["account"] == null)
            {
                Response.Redirect(Resource.Login);
                return;
            }
            AccountDTO accDTO = (AccountDTO)Session["account"];
            if (!"admin".Equals(accDTO.Roles))
            {
                Response.Redirect(Resource.Login);
                return;
            }
            if (!IsPostBack)
            {
                initComponent();
            }
        }

        private void initComponent()
        {
            AccountBLO accBLO = new AccountBLO();
            grid.DataSource = accBLO.getAccountList();
            grid.DataBind();
        }        

        protected void grid_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            string ID = e.Keys["ID"].ToString();
            Response.Redirect(Resource.AccountDetail+"?ID="+ID);
        }

        protected void grid_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int ID = 0;
            try { ID = Int32.Parse(e.Keys["ID"].ToString()); }
            catch (Exception) { }
            AccountBLO accBLO = new AccountBLO();
            AccountDTO accDTO = accBLO.getAccountByID(ID);
            accBLO.UpdateAccount(ID, accDTO.Email, accDTO.Name, accDTO.Password, "block");
            initComponent();
        }

        protected void CreateBtn_Command(object sender, CommandEventArgs e)
        {
            Response.Redirect(Resource.AccountDetail);
        }

        protected void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grid.PageIndex = e.NewPageIndex;
            initComponent();
        }
    }
}